import base64
import random
import string

from django.db.models import Max
from django.shortcuts import render
from django.http import JsonResponse
from rest_framework.parsers import JSONParser
from rest_framework.decorators import api_view

#鉴权
from django.core.cache import cache
from django.core.signing import Signer
from datetime import timedelta
from .models import dishes,employees,orders
#分页
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
# Create your views here.
#参数为空
def luoji(n):
    return n is None or str(n).strip()==''

#产生token
def createtoken(name):
    randomstr=''.join(random.choices(string.ascii_letters,k=8))
    token=Signer().sign(randomstr+name)
    cache.set(f'test_{name}',token,timeout=timedelta(minutes=100).total_seconds())
    return token
#校验token
def checktoken(request):
    reqtoken=request.META.get('HTTP_TOKEN')
    if reqtoken is None:
        return False,'xxxx'
    untoken=Signer().unsign(reqtoken)
    name=untoken[8:]
    cachetoken=cache.get(f'test_{name}')
    if cachetoken is None:
        return False,'xxxx'
    return True,name


#登录
@api_view(['POST'])
def login(request):
    data=JSONParser().parse(request)
    name=data.get('name')
    password=data.get('password')
    #对用户名加密
    bname=bytes(name,encoding='utf-8')
    b64name=base64.b64encode(bname).decode('utf-8')
    if employees.objects.filter(name=name).exists() is False:
        return JsonResponse({
            'code':403,
            'error':'用户不存在'
        })
    obj=employees.objects.get(name=name)
    if obj.password !=password:
        return JsonResponse({
            'code': 404,
            'error': '用户名或密码不正确'
        })
    token=createtoken(b64name)
    return JsonResponse({
        'code': 200,
        'msg': '登录成功',
        'token':token
    })

#分页
@api_view(['GET'])
def page(request):
    #请求第几页数据
    page=request.GET.get('page')
    #一页显示几条数据
    pagesize=request.GET.get('pagesize')
    #获取表中所有数据
    alldata=dishes.objects.filter()
    #分页设置
    pagedata=Paginator(alldata,pagesize)
    try:
        a=pagedata.page(page)
    except EmptyPage:
        a=pagedata.page(pagedata.num_pages)
    except PageNotAnInteger:
        a=pagedata.page(1)
    lis=[]
    for item in pagedata.object_list:
        lis.append({
            'id':item.id
        })
    return JsonResponse({
        'code':200,
        'msg':'操作成功',
        'data':lis,
        'items':alldata.count()

    })
























#分页
@api_view(['GET'])
def page(request):
    #请求第几页数据
    page=request.GET.get('page')
    #一页显示几条数据
    pagesize=request.GET.get('pageSize')
    name=request.GET.get('name')
    category=request.GET.get('category')
    if luoji(name) or luoji(category):
        #获取表中所有数据
        alldata=dishes.objects.filter()
    elif luoji(name)==True and luoji(category) is False:
        alldata = dishes.objects.filter(category=category)
    elif luoji(name)is False and luoji(category)==True:
        alldata = dishes.objects.filter(name=name)
    elif luoji(name)is False and luoji(category)is False:
        alldata = dishes.objects.filter(name=name,category=category)
    else:
        return JsonResponse({
            'code':403,
            'msg':'查询条件不符合规则'
        })
    #分页设置
    pageobjall=Paginator(alldata,pagesize)
    try:
        singleobj=pageobjall.page(page)
    #页码不存在
    except EmptyPage:
        singleobj=pageobjall.page(pageobjall.num_pages)
    #页码不是一个整型数字
    except PageNotAnInteger:
        singleobj=pageobjall.page(1)
    #定义一个空列表用于存数据用
    lis=[]
    for item in singleobj.object_list:
        lis.append({
            'id':item.id,
            'name':item.name,
            'price':item.price,
            'category':item.category,
            'description':item.description,
            'status':item.status,
            'create_time':item.create_time,
            'updata_time':item.updata_time,
        })
    return JsonResponse({
        'code':200,
        'msg':'查询成功',
        'data':lis,
        'items':alldata.count()
    })

#显示下拉内名称
@api_view(['GET'])
def tjchaxun(request):
    allcategory=dishes.objects.values('category').annotate(id=Max('id'))
    lis=[]
    for item in allcategory:
        lis.append({
            'id':item.get('id'),
            'name':item.get('category'),
        })
    return JsonResponse({
        'code':200,
        'data':lis
    })

#菜品添加
@api_view(['POST'])
def adddata(request):
    data=JSONParser().parse(request)
    name=data['name']
    price=data['price']
    category=data['category']
    description=data['description']
    status=data['status']
    #菜名是否存在
    if dishes.objects.filter(name=name).exists():
        return JsonResponse({
            'code':403,
            'msg':'该菜名已经存在'
        })
    #参数不能为空
    if luoji(name) or luoji(price) or luoji(category) or luoji(description) or luoji(status):
        return JsonResponse({
            'code': 404,
            'msg': '参数不能为空'
        })
    dishes(name=name,price=price,category=category,description=description,status=status).save()
    return JsonResponse({
        'code':200,
        'msg':'添加成功'
    })

#修改
@api_view(['PUT'])
def xiugai(request,id):
    data=JSONParser().parse(request)
    name=data.get('name')
    price=data.get('price')
    category=data.get('category')
    description=data.get('description')
    status=data.get('status')
    if luoji(name) or luoji(price) or luoji(category) or luoji(description) or luoji(status):
        return JsonResponse({
            'code':402,
            'msg':'参数不能为空'
        })
    if dishes.objects.filter(id=id).exists() is False:
        return JsonResponse({
            'code':400,
            'msg':'用户不存在'
        })
    obj=dishes.objects.get(id=id)
    obj.name=name
    obj.price=price
    obj.category=category
    obj.description=description
    obj.status=status
    obj.save()
    return JsonResponse({
        'code':200,
        'msg':'修改成功'
    })

#删除
@api_view(['DELETE'])
def deldata(request,id):
    obj=dishes.objects.filter(id=id)
    obj.delete()
    return JsonResponse({
        'code':200,
        'msg':'删除成功'
    })



